package com.example.exam.servlet;

import com.example.exam.dao.ExamDAO;
import com.example.exam.dao.ScoreDAO;
import com.example.exam.entity.Exam;
import com.example.exam.entity.Score;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * 考试Servlet
 */
@WebServlet("/exams/*")
public class ExamServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private ExamDAO examDAO = new ExamDAO();
    private ScoreDAO scoreDAO = new ScoreDAO();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("student") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        // 获取请求路径
        String pathInfo = request.getPathInfo();
        
        if (pathInfo == null || pathInfo.equals("/")) {
            // 获取学生ID
            String studentId = ((com.example.exam.entity.Student) session.getAttribute("student")).getStudentId();
            
            // 获取所有可用考试
            request.setAttribute("exams", examDAO.getAvailableExams(studentId));
            
            // 设置响应编码
            response.setContentType("text/html; charset=UTF-8");
            // 转发到考试列表页面
            request.getRequestDispatcher("/examList.jsp").forward(request, response);
        } else if (pathInfo.startsWith("/take/")) {
            // 获取考试ID
            String examIdStr = pathInfo.substring(6);
            try {
                int examId = Integer.parseInt(examIdStr);
                
                // 获取考试信息
                Exam exam = examDAO.getExamById(examId);
                if (exam == null) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
                
                // 检查考试状态
                Date now = new Date();
                if (now.before(exam.getStartTime())) {
                    request.setAttribute("error", "考试尚未开始");
                    request.getRequestDispatcher("/WEB-INF/views/examList.html").forward(request, response);
                    return;
                }
                
                if (now.after(exam.getEndTime())) {
                    request.setAttribute("error", "考试已结束");
                    request.getRequestDispatcher("/WEB-INF/views/examList.html").forward(request, response);
                    return;
                }
                
                // 检查学生是否已经参加过考试
                String studentId = ((com.example.exam.entity.Student) session.getAttribute("student")).getStudentId();
                Score score = scoreDAO.getScoreByExamId(studentId, examId);
                if (score != null) {
                    request.setAttribute("error", "你已经参加过该考试");
                    request.getRequestDispatcher("/WEB-INF/views/examList.html").forward(request, response);
                    return;
                }
                
                // 设置响应编码
                response.setContentType("text/html; charset=UTF-8");
                // 转发到考试页面
                request.setAttribute("exam", exam);
                request.getRequestDispatcher("/takeExam.jsp").forward(request, response);
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }
        } else if (pathInfo.startsWith("/result/")) {
            // 获取考试ID
            String examIdStr = pathInfo.substring(8);
            try {
                int examId = Integer.parseInt(examIdStr);
                
                // 获取学生ID
                String studentId = ((com.example.exam.entity.Student) session.getAttribute("student")).getStudentId();
                
                // 获取考试成绩
                Score score = scoreDAO.getScoreByExamId(studentId, examId);
                if (score == null) {
                    request.setAttribute("error", "未找到该考试成绩");
                    request.getRequestDispatcher("/WEB-INF/views/examList.html").forward(request, response);
                    return;
                }
                
                // 设置响应编码
                response.setContentType("text/html; charset=UTF-8");
                // 转发到成绩页面
                request.setAttribute("score", score);
                request.getRequestDispatcher("/examResult.jsp").forward(request, response);
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("student") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        // 获取考试ID
        String examIdStr = request.getParameter("examId");
        if (examIdStr == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        
        try {
            int examId = Integer.parseInt(examIdStr);
            
            // 获取学生信息
            com.example.exam.entity.Student student = (com.example.exam.entity.Student) session.getAttribute("student");
            
            // 获取考试信息
            Exam exam = examDAO.getExamById(examId);
            if (exam == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            
            // 模拟计算考试成绩（实际应用中应该根据学生答案计算）
            double scoreValue = Math.round(Math.random() * 40 + 60); // 生成60-100之间的随机分数
            
            // 创建成绩对象
            Score score = new Score();
            score.setStudentId(student.getStudentId());
            score.setStudentName(student.getName());
            score.setExamId(examId);
            score.setCourseName(exam.getCourseName());
            score.setScore(scoreValue);
            score.setExamDate(new Date());
            score.setStatus("已批改");
            
            // 保存成绩
            if (scoreDAO.addScore(score)) {
                // 重定向到成绩页面
                response.sendRedirect(request.getContextPath() + "/exams/result/" + examId);
            } else {
                request.setAttribute("error", "提交考试失败");
                request.getRequestDispatcher("/WEB-INF/views/examList.html").forward(request, response);
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}